import Vue from 'vue';
import Vuex from 'vuex';
import lodash from 'lodash';
import { getDictData, siteBaseInfo, getAttachUrl } from '@/api/openApi';
Vue.use(Vuex)
const state = {
	siteLogo: '',
	siteInfo: {},
	dictEnums: {},
	dictConst: {},
	authButton: [],
	siteConfig: [],
	defaultAvatar: ''
}

const actions = {
	init: ({ state, dispatch }) => {
		return new Promise(async (resolve, reject) => {
			await dispatch('getSiteBaseInfo');
			await dispatch('getOpenDictData');
			await dispatch('getSiteLogo');
			resolve();
		}).catch(() => {
			reject();
		})
	},

	//获取站点基本信息
	async getSiteBaseInfo({ commit, dispatch }) {
		let result = await siteBaseInfo().then(res => res.data);
		if (result.code === '0') {
			let datas = Vue.prototype.$detailData(result.data);
			document.title = datas['name'];
			commit('SET_SITE_INFO', datas);
		}
	},

	//获取数据字典数据
	async getOpenDictData({ commit }) {
		let result = await getDictData().then(res => res.data);
		if (result.code === '0') {
			let datas = !result.data ? {} : result.data[0];
			commit('SET_DICT_DATA', datas);
		}
	},

	//获取附件地址
	async getFileUrl({ commit }, id) {
		let result = await getAttachUrl(id).then(res => res.data);
		if (result.code === '0') {
			return !result.data ? null : result.data[0];
		} else {
			Promise.reject(new Error('faile'));
		}
	},

	//获取站点配置
	async getSiteLogo({ state, commit, dispatch }) {
		let webLogo = state.siteInfo.webLogo;
		if (!!webLogo && webLogo !== '-1') {
			let webLogoUrl = await dispatch('getFileUrl', webLogo);
			commit('SET_SITE_LOGO', webLogoUrl.setFilePath());
		} else {
			commit('SET_SITE_LOGO', require('@/assets/img/logo.png'));
		}
	},

	//获取默认用户头像
	async getDefaultAvatar({ state, dispatch }) {
		let userPic = state.siteInfo.userPic;
		if (!!userPic && userPic !== '-1') {
			let userPicUrl = await dispatch('getFileUrl', userPic);
			commit('SET_DEFAULT_AVATAR', userPicUrl.setFilePath());
		} else {
			commit('SET_DEFAULT_AVATAR', require('@/assets/img/avatar_image.png'));
		}
	}
}

const mutations = {
	SET_SITE_LOGO: (state, d) => {
		state.siteLogo = d;
	},
	SET_SITE_INFO: (state, d) => {
		state.siteInfo = d;
		Vue.prototype.$local.set('siteInfo', d);
	},
	SET_DICT_DATA: (state, d) => {
		state.dictEnums = d.enumKey;
		state.dictConst = d.constantKey;
		Vue.prototype.$local.set('dictEnums', d.enumKey);
		Vue.prototype.$local.set('dictConst', d.constantKey);
	},
	SET_SITE_CONFIG: (state, d) => {
		state.siteConfig = d;
		Vue.prototype.$local.set('siteConfig', d);
	},
	SET_DEFAULT_AVATAR: (state, d) => {
		state.defaultAvatar = d;
	}
}

export default { state, actions, mutations }